/**
 * 2018年12月1日下午12:04:10
 * @author 谢进财
 */
package com.baihang.framework.kit;

import java.util.Map;
import java.util.Map.Entry;

import com.baihang.framework.dao.Record;

/**
 * @author 数据库工具
 *
 */
public class DbKit {
	public static String recordToSaveSql(String tableName,Record record) {
		StringBuilder sqlCol = new StringBuilder("");
		StringBuilder sqlVal = new StringBuilder("");
		Map<String,Object> map = record.getColumns();
		for (Entry<String, Object> entry : map.entrySet()) {
			sqlCol.append(String.format("%s,", entry.getKey()));
			if(entry.getValue() instanceof String) {
				sqlVal.append(String.format("'%s',", entry.getValue()));
			}else if(entry.getValue() instanceof Integer) {
				sqlVal.append(String.format("%d,", entry.getValue()));
			}
		}
		String saveSql=String.format("insert into %s (%s) values (%s)", tableName,sqlCol.toString().substring(0, sqlCol.toString().length()-1),sqlVal.toString().substring(0, sqlVal.toString().length()-1));
		return saveSql;
	}
	public static String recordToUpdateSql(String tableName,String pk,Object pkVal,Record record) {
		StringBuilder sqlMap = new StringBuilder("");
		String updateSql="";
		Map<String,Object> map = record.getColumns();
		for (Entry<String, Object> entry : map.entrySet()) {
			if(entry.getValue() instanceof String) {
				sqlMap.append(String.format("'%s'='%s',",entry.getKey(),entry.getValue()));
			}else if(entry.getValue() instanceof Integer) {
				sqlMap.append(String.format("'%s'=%d,", entry.getKey(),entry.getValue()));
			}
		}
		if(pkVal instanceof String) {
			updateSql=String.format("update %s set %s where '%s'='%s' ", tableName,sqlMap.toString().substring(0, sqlMap.toString().length()-1),pk,pkVal);		   
		}else {
			updateSql=String.format("update %s set %s where '%s'=%d ", tableName,sqlMap.toString().substring(0, sqlMap.toString().length()-1),pk,pkVal);
		}
		return updateSql;
	}
	public static void main(String[] args) {
		Record record = new Record();
		record.set("abc", "123");
		record.set("def", 456);
		//String sql = DbKit.recordToSaveSql("xjc", record);
		String sql = DbKit.recordToUpdateSql("xjc","abc","123",record);
		System.err.println(sql);
	}
}
